/**
 * 注册脚本
 * 2019-12-18
 * by Molly
 */

try {
  var prevUrl = document.referrer || '';
  if (
    prevUrl != '' &&
    prevUrl.indexOf(MALL.Common.url.path_login) < 0 &&
    prevUrl.indexOf(MALL.Common.url.path_reg) < 0
  ) {
    var prevUrlArray = prevUrl.indexOf('www.anta.com') > 0 ? prevUrl.split('www.anta.com') : [];
    if (prevUrlArray.length > 1) {
      prevUrl = prevUrlArray[prevUrlArray.length - 1];
    }
    sessionStorage.setItem('anta_pc_before_login', prevUrl);
  }  
} catch (error) {
  console.error(error);     
}

var J = {
    USER_INPUT_MOBILE_EMPTY: '请输入注册手机号码',
    USER_INPUT_MOBILE_ERROR: '请正确输入注册手机号码',
    USER_INPUT_EMAIL_EMPTY: '请输入注册邮箱地址',
    USER_INPUT_EMAIL_ERROR: '请正确输入注册邮箱地址',
    CODE_INPUT_EMPTY: '请输入图片验证码',
    CODE_INPUT_ERROR: '验证码不正确',
    AGREE_CHECK_EMPTY: '请先阅读并接受隐私政策',
    SMSCODE_INPUT_EMPTY: '请输入短信验证码',
    /*old*/
    VERIFY_PASSWORD: '需要验证您的密码',
    VERIFY_PASSWORD_SUBMIT: '验证',
    USER_RES_ERROR: '用户名不正确',
    CODE_RES_ERROR: '验证码不正确',
    REFRESH_IMG_TIP: '点击图片刷新验证码',
    SMSCODE_INPUT_ERROR: '短信验证码不正确',
    PWD_INPUT_EMPTY: '请输入密码',
    /*new*/
  },
  url = {
    regCheckPhone: '/antacom/passport/regCheck',
    code: '/api.php?s=antacom/passport/code.html&w=120&h=36',
    regSmsRsend: '/antacom/passport/regsmsRsend',
    regCheckSms: '/antacom/passport/checksms',
    regMail: '/antacom/passport/regmail',
  },
  c = {
    form: $('#reg_form'),
    submit: $('#submit_button'),
    username: $('#user'),
    usernameBox: $('#user').parent(),
    pwd: $('#verify_e_pwd'),
    pwdBox: $('#verify_e_pwd').parent(),
    captcha: $('#captcha'),
    agree: $('#agree'), //隐私政策
    errorBox: $('#error-outcon'),
    errMs: $('#error-content'),
  },
  dm = {
    form: $('#verify_mobile_form'),
    username: $('#verify_m_user'),
    smscode: $('#verify_m_smscode'),
    smscodeBox: $('#verify_m_smscode').parent(),
    captcha: $('#verify_m_captcha'),
    errorBox: $('#error-verify-mobile'),
    errMs: $('#error-content-verify-mobile'),
    phone: '',
    timestamp: '',
    noncestr: '',
    signature: '',
    pwd: $('#verify_m_pwd'),
    pwdBox: $('#verify_m_pwd').parent(),
    timer: '',
    count: 60,
  };
function mixEmail(str) {
  var b = '@' + str.split('@')[1],
    a = str.split('@')[0];
  if (a.length > 3) {
    return a.substr(0, 3) + '****' + b;
  } else if (a.length <= 3 && a.length > 1) {
    return a.substr(0, a.length - 1) + '****' + b;
  } else {
    return a + '****' + b;
  }
}
//手机邮箱切换
function toggleRegType(_this) {
  if ($(_this).hasClass('active')) {
    return false;
  }
  $(_this).addClass('active').siblings('.active').removeClass('active');
  c.form.attr('data-type', $(_this).attr('data-type'));
  c.username.attr('placeholder', $(_this).attr('data-name')).val('');
  c.agree.find('#agree-check').prop('checked', false); //隐私政策
  $('.reg-type-name').html($(_this).attr('data-name'));
  $('#captcha-code').val('');
  verify_clear();
  changeImg();
  if ($(_this).attr('data-type') == 'email') {
    c.pwdBox.parent().show();
    c.pwd.val('');
  } else {
    c.pwdBox.parent().hide();
  }
}
//清楚错误标注
function verify_clear() {
  $('.labelbox').removeClass('err_label');
  c.errorBox.hide();
  dm.errorBox.hide();
}
//任何输入框点击
$('.labelbox').click(function () {
  verify_clear();
});
// 验证密码
function verify_pwd(x) {
  var text = x.pwd.val();
  var errMs = false;
  if (text == '') {
    errMs = J.PWD_INPUT_EMPTY;
  }
  if (errMs) {
    x.errorBox.show();
    x.errMs.html(errMs);
    x.pwdBox.addClass('err_label');
    return false;
  }
}
//验证码
function changeImg() {
  var time = new Date();
  src = url.code + '&' + time.getTime();
  $('#captcha-img').attr('src', src);
  $('#captcha-code').val('');
}
$('#captcha-img').click(function () {
  changeImg();
});
function verify_code(x) {
  var text = $('#captcha-code').val();
  var errMs = false;
  if (text == '') {
    errMs = J.CODE_INPUT_EMPTY;
  } else if (text.length != 4) {
    errMs = J.CODE_INPUT_ERROR;
  }
  if (errMs) {
    x.errorBox.show();
    x.errMs.html(errMs);
    $('.labelbox-captcha').addClass('err_label');
    return false;
  }
}
//Step1 账号
function verify_username() {
  var uname = c.username.val();
  var type = c.form.attr('data-type');
  var errMs = false;
  var reg1 = /^0?1[0-9][0-9]\d{8}$/;
  var reg2 =
    /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
  switch (type) {
    case 'mobile':
      if (uname == '') {
        errMs = J.USER_INPUT_MOBILE_EMPTY;
      } else if (uname.length > 36) {
        errMs = J.USER_INPUT_MOBILE_ERROR;
      } else if (!reg1.test(uname)) {
        errMs = J.USER_INPUT_MOBILE_ERROR;
      }
      break;
    case 'email':
      if (uname == '') {
        errMs = J.USER_INPUT_EMAIL_EMPTY;
      } else if (uname.length > 36) {
        errMs = J.USER_INPUT_EMAIL_ERROR;
      } else if (!reg2.test(uname)) {
        errMs = J.USER_INPUT_EMAIL_ERROR;
      }
      break;
    default:
  }
  if (errMs) {
    c.errorBox.show();
    c.errMs.html(errMs);
    c.usernameBox.addClass('err_label');
    return false;
  }
}
//确认隐私政策
function verify_agree() {
  var isAgree = c.agree.find('#agree-check').is(':checked');
  console.log(isAgree);
  var errMs = false;
  if (!isAgree) {
    errMs = J.AGREE_CHECK_EMPTY;
  }
  console.log(errMs);
  if (errMs) {
    c.errorBox.show();
    c.errMs.html(errMs);
    return false;
  }
}
//Step1 表单提交
c.form.submit(function () {
  if (c.submit.hasClass('disable')) {
    return false;
  }
  if (verify_username() === false) {
    return false;
  }
  if (verify_code(c) === false) {
    return false;
  }
  if (verify_agree() === false) {
    return false;
  }
  var type = c.form.attr('data-type');
  switch (type) {
    case 'mobile':
      c.submit.addClass('disable');
      MALL.Common.showLoading();
      $.ajax({
        type: 'POST',
        url: url.regCheckPhone,
        data: {
          username: c.username.val(),
          vcode: $('#captcha-code').val(),
        },
        success: function (data) {
          MALL.Common.hideLoading();
          c.submit.removeClass('disable');
          if (data.status == 0) {
            dm.phone = data.data.phone;
            dm.timestamp = data.data.timestamp;
            dm.noncestr = data.data.noncestr;
            dm.signature = data.data.signature;
            dm.username.val(data.data.phone);
            dm.captcha.html($('#captcha-code').parent().clone(true));
            dm.captcha.append($('#captcha-img').clone(true));
            c.captcha.html('');
            dm.form.show();
            $('#next_container').show().siblings('#first_container').hide();
            clearInterval(dm.timer);
            dm.count = 60;
            dm.form.find('.verify-sendbtn').addClass('disable');
            dm.timer = setInterval(function () {
              if (dm.count <= 1) {
                dm.form.find('.verify-sendbtn').removeClass('disable').html('重新发送');
                clearInterval(dm.timer);
              } else {
                dm.count--;
                dm.form.find('.verify-sendbtn').html('重新发送（' + dm.count + 's）');
              }
            }, 1000);
          } else {
            MALL.Common.message({ text: J[data.msg] ? J[data.msg] : data.msg, time: 3000 });
          }
          changeImg();
        },
        error: function (res) {
          MALL.Common.hideLoading();
          c.submit.removeClass('disable');
          changeImg();
        },
      });
      break;
    case 'email':
      if (verify_pwd(c) === false) {
        return false;
      }
      var password = hex_md5(c.pwd.val());
      c.submit.addClass('disable');
      MALL.Common.showLoading();
      $.ajax({
        type: 'POST',
        url: url.regMail,
        data: {
          email: c.username.val(),
          pwdcode: password,
          vcode: $('#captcha-code').val(),
        },
        success: function (data) {
          c.submit.removeClass('disable');
          MALL.Common.hideLoading();
          if (data.status == 0) {
            $('.send-email-wrp').find('.verify-email-masked').html(mixEmail(c.username.val()));
            $('#first_container,#next_container').hide();
            $('#send_email_container').show();
          } else {
            MALL.Common.message({ text: J[data.msg] ? J[data.msg] : data.msg, time: 3000 });
            changeImg();
          }
        },
        error: function () {
          MALL.Common.hideLoading();
          c.submit.removeClass('disable');
          changeImg();
        },
      });
      break;
    default:
  }
  c.submit.removeClass('disable');
  return false;
});
//Step2-mobile 重新短信验证码
function resendSms(_this) {
  if ($(_this).hasClass('disable')) {
    return false;
  }
  //重新发送
  $.ajax({
    type: 'POST',
    url: url.regSmsRsend,
    data: {
      phone: dm.phone,
      timestamp: dm.timestamp,
      noncestr: dm.noncestr,
      signature: dm.signature,
    },
    success: function (data) {
      if (data.status == 0) {
        MALL.Common.message({ text: data.msg, time: 2000 });
        clearInterval(dm.timer);
        dm.count = 60;
        dm.form.find('.verify-sendbtn').addClass('disable');
        dm.timer = setInterval(function () {
          if (dm.count <= 1) {
            dm.form.find('.verify-sendbtn').html('重新发送').removeClass('disable');
            clearInterval(dm.timer);
          } else {
            dm.count--;
            dm.form.find('.verify-sendbtn').html('重新发送（' + dm.count + 's）');
          }
        }, 1000);
      } else {
        MALL.Common.message({ text: J[data.msg] ? J[data.msg] : data.msg, time: 3000 });
      }
      changeImg();
    },
    error: function () {
      changeImg();
    },
  });
  return false;
}
//Step2-mobile 验证 短信验证码
function verify_smscode() {
  var text = dm.smscode.val();
  var errMs = false;
  if (text == '') {
    errMs = J.SMSCODE_INPUT_EMPTY;
  } else if (text.length != 6) {
    errMs = J.SMSCODE_INPUT_ERROR;
  }
  if (errMs) {
    dm.errorBox.show();
    dm.errMs.html(errMs);
    dm.smscodeBox.addClass('err_label');
    return false;
  }
}
//Step2-mobile 表单提交
function mobileSubmit(_this) {
  if ($(_this).hasClass('disable')) {
    return false;
  }
  if (verify_smscode() === false) {
    return false;
  } else if (verify_pwd(dm) === false) {
    return false;
  } else if (dm.captcha.is(':visible') && verify_code(dm) === false) {
    return false;
  }
  if (!dm.captcha.is(':visible')) {
    $('#captcha-code').val('');
  }
  var password = hex_md5(dm.pwd.val());
  $(_this).addClass('disable');
  MALL.Common.showLoading();
  $.ajax({
    type: 'POST',
    url: url.regCheckSms,
    data: {
      phone: dm.phone,
      timestamp: dm.timestamp,
      noncestr: dm.noncestr,
      signature: dm.signature,
      smscode: dm.smscode.val(),
      pwdcode: password,
      vcode: $('#captcha-code').val(),
    },
    success: function (data) {
      MALL.Common.hideLoading();
      $(_this).removeClass('disable');
      console.log("anta_pc_login:",data);
      if (data.status == 0) {
        try {
          var prevUrl = sessionStorage.getItem('anta_pc_before_login');
          location.href = prevUrl || data.url;
          console.log("anta_pc_before_login:",prevUrl);
        } catch (error) {
          console.error(error);
          location.href = data.url;
        }
      } else {
        MALL.Common.message({ text: J[data.msg] ? J[data.msg] : data.msg, time: 3000 });
        if (data.showCode) {
          dm.captcha.show();
          $('#captcha-code').val('');
        }
      }
      changeImg();
    },
    error: function () {
      MALL.Common.hideLoading();
      $(_this).removeClass('disable');
      changeImg();
    },
  });
}
